//
//  AppDelegate+ApplicationWillEnterForeground.m
//  mcrmSAAS
//
//  Created by wjxfhxy on 15-6-26.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "AppDelegate+ApplicationWillEnterForeground.h"

#import "AppDelegate+Tip.h"

#import "AppDelegate+Private.h"

#import "ProgressGradientView.h"

@implementation AppDelegate (ApplicationWillEnterForeground)

-(void)setEnterForegroundCheckTimer:(NSTimer*)timer
{
    [self setAssociatedRetainNonatomicValue:timer withKey:"EnterForegroundCheckTimer"];
}

-(NSTimer*)enterForegroundCheckTimer
{
    NSTimer *timer = [self associatedValueForKey:"EnterForegroundCheckTimer"];
    return timer;
}

-(void)fireEnterForegroundCheckTimer
{
    NSTimer *timer = [self enterForegroundCheckTimer];
    if(timer == nil)
    {
        timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(enterForegroundResumeFun) userInfo:nil repeats:YES];
        [timer setFireDate:[NSDate dateWithTimeIntervalSince1970:[[NSDate date] timeIntervalSince1970] + 5]];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [self setEnterForegroundCheckTimer:timer];
    }
}

-(void)invalidateEnterForegroundCheckTimer
{
    NSTimer *timer = [self enterForegroundCheckTimer];
    [timer invalidate];
    [self setEnterForegroundCheckTimer:nil];
}

-(NSUInteger)enterForegroundCheckCount
{
    NSUInteger count = [[self associatedValueForKey:"EnterForegroundCheckCount"] unsignedIntegerValue];
    return count;
}

-(void)setEnterForegroundCheckCount:(NSUInteger)checkCount
{
    [self setAssociatedRetainNonatomicValue:@(checkCount) withKey:"EnterForegroundCheckCount"];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [_timer invalidate];
    _timer = nil;
    
    if (_bgtask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:_bgtask];
        _bgtask = UIBackgroundTaskInvalid;
    }
    
    [[UIApplication sharedApplication] clearKeepAliveTimeout];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    [XMSSingleQueue runAsyncBlock:^
    {
        [CRequestChannelPoolShell startRequestRunLoop];
        
        if ([XLGContext context].m_bLogined == YES)
        {
            if([XLGContext context].m_bIsofflinelogin == NO)
            {
                if([XMSBackgroundMaintain stopMaintainIfMaintaining]==YES)
                    return;
            }
            
            DispatchMainThreadAsync(^
            {
                [self resumeFun];
            });
        }
    }];
}

-(void)resumeFun
{
    if([XLGContext context].m_bLogined == NO)
        return ;
    
    if (YES == [[XMSNetWorkReachability reachability] isNotReachable])
    {
        [XLGContext context].m_bIsoffline = YES;
        [AppDelegate presentBottomAutoCloseTipViewWithTip:@"当前网络不可用，\r请检查网络"];
        
        if (_reachability == nil)
        {
            _reachability = [XMSNetWorkReachability reachabilityForInternetConnection];
            [_reachability reachabilityChangedBlock:^(XMSNetWorkReachability *reachability)
            {
                if ([reachability isNotReachable] == NO)
                {
                    [reachability stopNotifier];
                    [self enterForegroundResumeFun];
                }
            }];
        }
        if ([_reachability isNotReachable] == NO)
            [self enterForegroundResumeFun];
        else
            [_reachability startNotifier];
    }
    else
        [self enterForegroundResumeFun];
    
}

-(void)enterForegroundResumeFun
{
    if([XLGContext context].m_bLogined == NO)
        return ;
    
    [ProgressGradientView start];
    
    if([XLGContext context].m_bIsofflinelogin == NO)
    {
        [XLGUpdateSession foregroundCheckSessionIsTimeoutAsyncCompletion:^(NSInteger nResult, BOOL bIstimeout)
        {
            UIApplicationState state = [UIApplication sharedApplication].applicationState;
            
            DispatchMainThreadAsync(^
            {
                [ProgressGradientView stop];
                
                [self invalidateEnterForegroundCheckTimer];
                
                if (state == UIApplicationStateBackground)
                    return;
            
                switch (nResult)
                {
                    case YES:
                    {
                        [XLGContext context].m_bIsoffline = NO;
                        
                        [AppDelegate presentBottomAutoCloseTipViewWithTip:@"连接成功"];
                        
                        if (bIstimeout == NO)
                        {
                            [XMSSingleQueue runAsyncBlock:^
                            {
                                if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
                                    return;
                                
                                [XLGUpdateSession resumeUpdateSessionTimer];
                                
                                [XLGSendQueueManager resumeSendQueueManager];
                                
                                [XLGDownloadManager resumeDownloadManger];
                                
                                [XLGServiceTime startService];
                                
                                [[XMSNetWorkReachability reachability] startNotifier];
                                
                                [RSWMessageOperation resumeOperatePushNotification];
                           
                                [RSWMessageOperation bindPushAsyncCompletion:^(NSInteger nResult, BOOL bResult, NSError *error)
                                 {
                                     [RSWMessageOperation getChatOfflineMessage:YES complete:^(NSInteger nResult){}];
                                 }];
                            }];
                        }
                        else
                        {
                        }
                        
                        break;
                    }
                    case TERMINATEREADWRITE:
                    {
                        break;
                    }
                    case PROTOCOLRETOBJNIL:
                    {
                        [XLGContext context].m_bIsoffline = YES;
                        [AppDelegate presentBottomAutoCloseTipViewWithTip:@"当前服务不可用"];
                        break;
                    }
                    case NETWORKOFFLINE:
                    {
                        [XLGContext context].m_bIsoffline = YES;
                        [AppDelegate presentBottomAutoCloseTipViewWithTip:@"当前网络不可用，\r请检查网络"];
                        [_reachability startNotifier];
                        break;
                    }
                    default:
                    {
                        [self enterForegroundResumeCheck];
                        
                        [XLGContext context].m_bIsoffline = YES;
                        [AppDelegate presentBottomAutoCloseTipViewWithTip:@"登录超时，\r应用处于离线操作状态"];
                        break;
                    }
                }
            });
        }];
    }
    else
    {
        //TODO
    }
}

-(BOOL)enterForegroundResumeCheck
{
    if([self enterForegroundCheckCount] >= 2)
    {
        [self invalidateEnterForegroundCheckTimer];
        [self setEnterForegroundCheckCount:0];
        return NO;
    }
    else
    {
        [self fireEnterForegroundCheckTimer];
        [self setEnterForegroundCheckCount:[self enterForegroundCheckCount] + 1];
    }
    return YES;
}

@end
